<template>
  <div class="p-6px">
    <el-card class="rounded-md" shadow="never">
      <!-- 搜索条件 -->
      <el-form v-show="showSearch" :inline="true" id="searchFormId" @submit.prevent>
        <el-form-item label="规格名称" prop="username">
          <el-input placeholder="请输入规格名称" v-model="searchParams.name" clearable style="width: 200px"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="search" plain v-debounce="handleSearch">搜索</el-button>
          <el-button type="danger" icon="refresh" plain v-throttle="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 表格头部按钮 -->
      <el-row :gutter="10">
        <el-col :span="1.5" v-auth="['system:role:add']">
          <el-button type="primary" icon="plus" plain @click="handleAdd()">新增</el-button>
        </el-col>
        <KoiToolbar v-model:showSearch="showSearch" @refresh-table="handleListPage"></KoiToolbar>
      </el-row>

      <br />
      <el-table
        v-loading="loading"
        v-adaptive
        border
        :data="tableList"
        empty-text="暂时没有数据哟"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="序号" prop="id" width="80px" align="center" type="index"></el-table-column>
        <el-table-column label="模板名称" prop="name" align="center" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column label="参数值" prop="icon" align="center">
          <template #default="scope">
            <span v-for="(item, index) in scope.row.value" :key="index">
              {{ item.label }} : {{ item.value }}
              <br />
            </span>
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          align="left"
          width="350"
          fixed="right"
          v-auth="['system:role:update', 'system:role:delete']"
        >
          <template #default="{ row }">
            <el-button type="primary" size="small" plain @click="handleUpdate(row)" v-auth="['system:role:update']">
              修改
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <br />
      <!-- 分页 -->
      <el-pagination
        background
        v-model:current-page="searchParams.pageNo"
        v-model:page-size="searchParams.pageSize"
        v-show="total > 0"
        :page-sizes="[10, 20, 50, 100, 200]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleListPage"
        @current-change="handleListPage"
      />

      <!-- 添加 OR 修改 -->
      <KoiDrawer
        ref="koiDrawerRef"
        :title="title"
        @koi-confirm="handleConfirm"
        @koi-cancel="handleCancel"
        :loading="confirmLoading"
        :size="1000"
      >
        <template #content>
          <el-form ref="formRef" :rules="rules" :model="form" label-width="80px" status-icon>
            <el-form-item label="模板名称" prop="title">
              <el-input v-model="form.name" placeholder="请输入模板名称" clearable />
            </el-form-item>
            <el-form-item label="模板值" prop="level">
              <div>
                <el-button type="primary" @click="addAttr()" link>新的参数</el-button>
              </div>
              <el-table :data="form.value" stripe style="width: 100%" :editable="true" border>
                <el-table-column prop="title" label="参数名称" align="center">
                  <template #default="scope">
                    <el-input type="text" v-model="scope.row.label" clearable style="text-align: center" />
                  </template>
                </el-table-column>
                <el-table-column prop="item" label="参数值" align="center">
                  <template #default="scope">
                    <div style="display: flex; flex-wrap: wrap">
                      <el-input type="text" v-model="scope.row.value" clearable style="text-align: center; " />
                    </div>
                  </template>
                </el-table-column>
                <el-table-column prop="item" label="操作" align="center">
                  <template #default="scope">
                    <el-button type="primary" @click="removeAttr(scope.row, scope.$index)" link>删除</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-form-item>
          </el-form>
        </template>
      </KoiDrawer>
    </el-card>
  </div>
</template>

<script setup lang="ts" name="memberLevelPage">
import { onMounted, reactive, ref } from "vue";
import { koiMsgError, koiMsgWarning, koiNoticeError } from "@/utils/koi.ts";
import { add, read, listPage, update } from "@/api/pms/attrtpl/index.ts";
import { koiDatePicker } from "@/utils/index.ts";

// 数据表格加载页面动画
const loading = ref(false);
/** 是否显示搜索表单 */
const showSearch = ref<boolean>(true); // 默认显示搜索条件
// 数据表格数据
const tableList = ref<any>([]);
// 查询参数
const searchParams = ref({
  pageNo: 1, // 第几页
  pageSize: 10, // 每页显示多少条
  name: ""
});

const total = ref<number>(0);

// 重置搜索参数
const resetSearchParams = () => {
  searchParams.value = {
    pageNo: 1,
    pageSize: 10,
    name: ""
  };
};

/** 搜索 */
const handleSearch = () => {
  searchParams.value.pageNo = 1;
  handleListPage();
};

/** 重置 */
const resetSearch = () => {
  resetSearchParams();
  handleListPage();
};

// 时间
const dateRange = ref();
/** @current-change：点击分页组件页码发生变化：例如：切换第2、3页 OR 上一页 AND 下一页 OR 跳转某一页 */
/** @size-change：点击分页组件下拉选中条数发生变化：例如：选择10条/页、20条/页等 */
// 分页查询，@current-change AND @size-change都会触发分页，调用后端分页接口
/** 数据表格 */
const handleListPage = async () => {
  try {
    loading.value = true;
    tableList.value = []; // 重置表格数据
    const res: any = await listPage(koiDatePicker(searchParams.value, dateRange.value, "created"));
    tableList.value = res.data.records;
    total.value = res.data.total;
    loading.value = false;
  } catch (error) {
    console.log(error);
    koiNoticeError("数据查询失败，请刷新重试");
  }
};

onMounted(() => {
  // 获取数据表格数据
  handleListPage();
});

/** 添加 */
const handleAdd = () => {
  // 重置表单
  resetForm();
  // 标题
  title.value = "添加";
  koiDrawerRef.value.koiOpen();
};

/** 回显数据 */
const handleEcho = async (id: any) => {
  if (id == null || id == "") {
    koiMsgWarning("请选择需要修改的数据");
    return;
  }
  try {
    const res: any = await read(id);
    form.value = res.data;
  } catch (error) {
    koiNoticeError("数据获取失败，请刷新重试");
    console.log(error);
  }
};

/** 修改 */
const handleUpdate = async (row?: any) => {
  // 重置表单
  resetForm();
  // 标题
  title.value = "修改";
  const id = row.id;
  if (id == null || id == "") {
    koiMsgError("请选中需要修改的数据");
  }
  handleEcho(id);
  koiDrawerRef.value.koiOpen();
};

/** 添加 AND 修改抽屉 */
const koiDrawerRef = ref();
// 标题
const title = ref("");
// form表单Ref
const formRef = ref<any>();

// form表单
let form = ref<any>({
  name: "",
  value: []
});

/** 清空表单数据 */
const resetForm = () => {
  form.value = {
    name: "",
    value: []
  };
};

/** 表单规则 */
const rules = reactive({});

// 确定按钮是否显示loading
const confirmLoading = ref(false);
/** 确定  */
const handleConfirm = () => {
  if (!formRef.value) return;
  confirmLoading.value = true;
  (formRef.value as any).validate(async (valid: any) => {
    if (valid) {
      try {
        console.log(`form.value`, JSON.stringify(form.value));
        //过滤空值
        form.value.value = form.value.value.filter((r: any) => {
          return r.label;
        });
        if (form.value.id != null && form.value.id != "") {
          await update(form.value);
        } else {
          await add(form.value);
        }
        resetForm();
        handleListPage();
        koiDrawerRef.value.koiQuickClose();
      } catch (error) {
        console.log(error);
        confirmLoading.value = false;
        koiNoticeError("操作失败，请刷新重试");
      } finally {
        confirmLoading.value = false;
      }
    } else {
      koiMsgError("验证失败，请检查填写内容");
      confirmLoading.value = false;
    }
  });
};

/** 取消 */
const handleCancel = () => {
  koiDrawerRef.value.koiClose();
};
const removeAttr = (_row: any, valueIndex: any) => {
  form.value.value.splice(valueIndex, 1);
};
const addAttr = () => {
  form.value.value.push({
    label: "",
    value: ""
  });
};
</script>

<style lang="scss" scoped>

</style>
